import { createRouter, createWebHashHistory, Router } from 'vue-router'
import { useMenu, useStaff, useToken } from '@/store'
import { MenuList } from '@/ts/type'
import { ref } from 'vue'
import { Notification } from '@/plugins/element'
import { storeToRefs } from 'pinia'

const reFresh = ref<boolean>(true)
const Login = () => import('@/views/login.vue')
const Home = () => import('@/views/Home.vue')
const routes = [
  {
    path: '/',
    name: '/',
    redirect: '/home'
  },
  {
    path: '/Login',
    name: 'login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/home',
    name: 'home',
    redirect: '/base',
    component: Home,
  },
  {
    path: '/500',
    component: () => import('@/views/500.vue'),
    meta: { title: '网络连接错误' }
  },
  {
    path: '/:pathMatch(.*)',
    hidden: true,
    component: () => import('@/views/404.vue'),
    meta: { title: '资源未找到' }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  // @ts-ignore
  routes
})

const dealMenu = (menuList: MenuList[], router: Router) => {
  menuList.forEach(res => {
    router.addRoute('home', {
      path: res.path,
      name: res.name,
      component: () => import(`@/views/${res.component}.vue`)
    })
    if (res.children) {
      dealMenu(res.children, router)
    }
  })
  reFresh.value = false
}

const hasToken = (): boolean => {
  const Token = useToken()
  return Boolean(Token.token)
}

router.beforeEach(async (to, from, next) => {
  const Menu = useMenu()
  const Staff = useStaff()
  const { list: List } = storeToRefs(Menu)
  if (from.name === 'login') {
    await Staff.getInfo()
  }
  if (!hasToken() && to.path !== '/login') {
    Notification.error('系统监测未登录，请重新登录')
    return next('/login')
  }
  if (hasToken() && to.path === '/login') {
    Notification.warning('您已登录,请退出登录后执行操作')
    return next('/')
  }
  if (hasToken() && to.path !== '/login') {
    if (reFresh.value) {
      if (List.value.length === 0) {
        await Staff.getInfo()
      }
      await dealMenu(List.value, router)
      reFresh.value = false
      return next({ ...to, replace: true })
    }
    return next()
  }
  next()
})

router.afterEach(to => {
  if (typeof to.meta?.title === 'string') {
    document.title = to.meta?.title
  } else {
    document.title = '南宫亚定点医院业务管理系统'
  }
})

export default router


